<?php
class ControllerCommunityProfile extends Controller{
    public function index(){
        $this->language->load('community/profile');
        $this->language->load('community/community_header');

        $this->document->setTitle($this->language->get('heading_title'));

        $this->load->model('community/profile');

        //detect if user login
        if($this->customer->isLogged()){
            $this->data['is_user_login']=TRUE;
        }else{
            $this->data['is_user_login']=FALSE;
        }

        if(!isset($this->request->get['uid']) || $this->request->get['uid']==0){
            $this->redirect($this->url->link('error/not_found'));
        }

        //get member info
        $result=$this->model_community_profile->getMemberInfo($this->request->get);

        if(!isset($result['username'])){
            $this->redirect($this->url->link('error/not_found'));
        }

        $this->data['breadcrumbs']=array();

        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('common/home'),
            'text'      =>      $this->language->get('text_home'),
            'separator'=>      FALSE
        );

        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('community/community'),
            'text'      =>      $this->language->get('text_community'),
            'separator' =>      $this->language->get('text_separator')
        );

        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('community/profile','uid=' .  $this->request->get['uid'],'SSL'),
            'text'      =>      sprintf($this->language->get('text_profile'),$result['username']),
            'separator' =>      $this->language->get('text_separator')
        );

        $this->data['headline_link']=$this->url->link('community/profile','uid=' .  $this->request->get['uid'],'SSL');
        $this->data['topics_link']=$this->url->link('community/profile','action=t&uid=' .  $this->request->get['uid'],'SSL');
        $this->data['posts_link']=$this->url->link('community/profile','action=p&uid=' .  $this->request->get['uid'],'SSL');
        $this->data['member_information_link']=$this->url->link('community/profile','action=mi&uid=' .  $this->request->get['uid'],'SSL');

        $this->data['headline_name']=sprintf($this->language->get('text_profile'),$result['username']);
        $this->data['text_member_information']=$this->language->get('text_member_information');
        $this->data['text_topics']=$this->language->get('text_topics');
        $this->data['text_posts']=$this->language->get('text_posts');
        $this->data['text_latest_post']=$this->language->get('text_latest_post');
        $this->data['text_by']=$this->language->get('text_by');
        $this->data['text_never']=$this->language->get('text_never');

        $this->data['navi_mi_active']='';
        $this->data['navi_t_active']='';
        $this->data['navi_p_active']='';

        if(!isset($this->request->get['action'])){
            $this->request->get['action']='mi';
        }

        switch($this->request->get['action']){
            case 'mi':
                $this->memberInformation($result);
                break;
            case 't':
                $this->topic();
                break;
            case 'p':
                $this->post();
                break;

        }

        if(file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/community/profile.tpl')){
            $this->template=$this->config->get('config_template') . '/template/community/profile.tpl';
        }else{
            $this->template='default/template/community/profile.tpl';
        }

        $this->children = array(
            'common/column_left',
            'common/column_right',
            'common/content_top',
            'common/content_bottom',
            'common/footer',
            'common/header',
            'community/community_header'
        );

        $this->response->setOutput($this->render());
    }

    private function memberInformation($memberInfoResult){
        $this->data['content_type']='mi';
        $this->data['navi_mi_active']=' class="member-profile-active"';

        $this->data['text_send_pm']=$this->language->get('text_send_pm');
        $this->data['text_user_activity']=$this->language->get('text_user_activity');
        $this->data['text_joined']=$this->language->get('text_joined');
        $this->data['text_last_visited']=$this->language->get('text_last_visited');
        $this->data['text_last_post']=$this->language->get('text_last_post');
        $this->data['text_user_rank']=$this->language->get('text_user_rank');
        $this->data['text_user_group']=$this->language->get('text_user_group');
        $this->data['text_email_verification']=$this->language->get('text_email_verification');
        $this->data['text_user_statics']=$this->language->get('text_user_statics');
        $this->data['text_basic_information']=$this->language->get('text_basic_information');
        $this->data['text_icq']=$this->language->get('text_icq');
        $this->data['text_aol']=$this->language->get('text_aol');
        $this->data['text_msn']=$this->language->get('text_msn');
        $this->data['text_yahoo']=$this->language->get('text_yahoo');
        $this->data['text_jabber']=$this->language->get('text_jabber');
        $this->data['text_location']=$this->language->get('text_location');
        $this->data['text_occupation']=$this->language->get('text_occupation');
        $this->data['text_interests']=$this->language->get('text_interests');
        $this->data['text_age']=$this->language->get('text_age');

        $this->data['send_pm_link']=$this->url->link('community/ucp','mode=pm&action=cm&uid=' . $this->request->get['uid'],'SSL');
        $this->data['topic_link']=$this->url->link('community/profile','action=t&uid=' . $this->request->get['uid'],'SSL');
        $this->data['post_link']=$this->url->link('community/profile','action=p&uid=' . $this->request->get['uid'],'SSL');

        $this->data['memberInfo']=array(
            'user_type'          =>      $memberInfoResult['user_type'],
            'user_ip'           =>      $memberInfoResult['user_ip'],
            'user_regdate'      =>      date($this->language->get('date_time_format_long'),$memberInfoResult['user_regdate']),
            'user_lastvisit'    =>      date($this->language->get('date_time_format_long'),$memberInfoResult['user_lastvisit']),
            'user_lastpost_time'=>      date($this->language->get('date_time_format_long'),$memberInfoResult['user_lastpost_time']),
            'user_topics'       =>      $memberInfoResult['user_topics'],
            'user_posts'        =>      $memberInfoResult['user_posts'],
            'role'              =>      $memberInfoResult['role_title']
        );

        if(isset($memberInfoResult['rank_title'])){
            $this->data['memberInfo']['rank_title']=$memberInfoResult['rank_title'];
        }else{
            $this->data['memberInfo']['rank_title']=$this->language->get('text_no_rank_title');
        }

        if(!empty($memberInfoResult['user_avatar'])){
            $this->data['memberInfo']['user_avatar']=$memberInfoResult['user_avatar'];
        }else{
            $this->data['memberInfo']['user_avatar']='catalog/view/theme/default/image/general/avatar.gif';
        }

        if(!empty($memberInfoResult['user_from'])){
            $this->data['memberInfo']['user_from']=$memberInfoResult['user_from'];
        }else{
            $this->data['memberInfo']['user_from']=$this->language->get('text_not_defined');
        }

        if(!empty($memberInfoResult['user_icq'])){
            $this->data['memberInfo']['user_icq']=$memberInfoResult['user_icq'];
        }else{
            $this->data['memberInfo']['user_icq']=$this->language->get('text_not_defined');
        }

        if(!empty($memberInfoResult['user_aim'])){
            $this->data['memberInfo']['user_aim']=$memberInfoResult['user_aim'];
        }else{
            $this->data['memberInfo']['user_aim']=$this->language->get('text_not_defined');
        }

        if(!empty($memberInfoResult['user_yim'])){
            $this->data['memberInfo']['user_yim']=$memberInfoResult['user_yim'];
        }else{
            $this->data['memberInfo']['user_yim']=$this->language->get('text_not_defined');
        }

        if(!empty($memberInfoResult['user_msnm'])){
            $this->data['memberInfo']['user_msnm']=$memberInfoResult['user_msnm'];
        }else{
            $this->data['memberInfo']['user_msnm']=$this->language->get('text_not_defined');
        }

        if(!empty($memberInfoResult['user_jabber'])){
            $this->data['memberInfo']['user_jabber']=$memberInfoResult['user_jabber'];
        }else{
            $this->data['memberInfo']['user_jabber']=$this->language->get('text_not_defined');
        }

        if(!empty($memberInfoResult['user_occ'])){
            $this->data['memberInfo']['user_occ']=$memberInfoResult['user_occ'];
        }else{
            $this->data['memberInfo']['user_occ']=$this->language->get('text_not_defined');
        }

        if(!empty($memberInfoResult['user_interests'])){
            $this->data['memberInfo']['user_interests']=$memberInfoResult['user_interests'];
        }else{
            $this->data['memberInfo']['user_interests']=$this->language->get('text_not_defined');
        }

        if(!empty($memberInfoResult['user_birthday'])){
            //calculate age
            list($bm,$bd,$by)=explode('-',$memberInfoResult['user_birthday']);
            $cm=date('n');
            $cd=date('j');
            $age=date('Y')-$by-1;

            if ($cm>$bm || $cm=$bm && $cd>$bd) $age++;
            $this->data['memberInfo']['age']=$age;
        }else{
            $this->data['memberInfo']['age']=$this->language->get('text_not_defined');
        }

        if(empty($memberInfoResult['user_actkey'])){
             $this->data['memberInfo']['email_verification']=$this->language->get('text_yes');
        }else{
            $this->data['memberInfo']['email_verification']=$this->language->get('text_no');
        }
    }

    private function topic(){
        $this->data['content_type']='t';
        $this->data['navi_t_active']=' class="member-profile-active"';

        $this->data['text_topic']=$this->language->get('text_topic');
        $this->data['text_forum']=$this->language->get('text_forum');
        $this->data['text_replies']=$this->language->get('text_replies');
        $this->data['text_views']=$this->language->get('text_views');
        $this->data['text_last_post']=$this->language->get('text_last_post');
        $this->data['text_no_topics']=$this->language->get('text_no_topics');

        //pagination
        $url='action=t&uid=' . $this->request->get['uid'];
        $pagination = new Pagination();

        $pagination->total=$this->model_community_profile->getTopicTotal($this->request->get);

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

        $pagination->page = $page;
        $pagination->limit = 20;
        $pagination->url = $this->url->link('community/profile', $url . '&page={page}');

        $this->data['pagination'] = $pagination->render();

        $start=($page-1)*$pagination->limit;

        $results=$this->model_community_profile->getTopicInfo($this->request->get,$start,$pagination->limit);

        if(empty($results)){
            $this->data['has_topics']=FALSE;
        }else{
            $this->data['has_topics']=TRUE;
        }

        $this->data['topic_infos']=array();

        $i=0;

        foreach($results as $result){
            $this->data['topic_infos'][]=array(
                'topic_title'            =>      $result['topic_title'],
                'topic_time'             =>      date($this->language->get('date_time_format_long'),$result['topic_time']),
                'forum_name'             =>      $result['forum_name'],
                'topic_replies'          =>      $result['topic_replies'],
                'topic_views'            =>      $result['topic_views'],
                'topic_last_poster_id'   =>      $result['topic_last_poster_id'],
                'topic_last_poster_name' =>      $result['topic_last_poster_name'],
                'topic_last_post_time'   =>      date($this->language->get('date_time_format_long'),$result['topic_last_post_time'])
            );

            $this->data['topic_infos'][$i]['member_link']=$this->url->link('community/profile','uid=' . $result['topic_last_poster_id'],'SSL');
            $this->data['topic_infos'][$i]['forum_link']=$this->url->link('community/viewforum','fid=' . $result['forum_id'],'SSL');
            $this->data['topic_infos'][$i]['topic_link']=$this->url->link('community/viewtopic','fid=' . $result['forum_id'] . '&tid=' . $result['topic_id'],'SSL');

            if(!empty($results)){
                if(time()-$result['topic_last_post_time']>(int)$this->config->get('topics_be_read_time')){
                    switch($result['topic_type']){
                        case '0':
                            $this->data['topicStatus'][]= 'topic_read';
                            break;
                        case '1':
                            $this->data['topicStatus'][]= 'topic_sticky_read';
                            break;
                    }

                    $this->data['text_topic_status'][]=$this->language->get('text_topic_read');

                }else{
                    if(isset($result['mark_time'])){

                        switch($result['topic_type']){
                            case '0':
                                $this->data['topicStatus'][]=($result['mark_time']>$result['topic_last_post_time']) ? 'topic_read' : 'topic_unread';
                                break;
                            case '1':
                                $this->data['topicStatus'][]=($result['mark_time']>$result['topic_last_post_time']) ? 'topic_sticky_read' : 'topic_sticky_unread';
                        }
                        $this->data['text_topic_status'][]=($result['mark_time']>$result['topic_last_post_time']) ? $this->language->get('text_topic_read') : $this->language->get('text_topic_unread');
                    }else{
                        if(!$this->customer->isLogged()){
                            $this->data['topicStatus'][]='topic_read';
                            $this->data['text_topic_status'][]=$this->language->get('text_topic_read');
                        }else{
                            switch($result['topic_type']){
                                case '0':
                                    $this->data['topicStatus'][]= 'topic_unread';
                                    break;
                                case '1':
                                    $this->data['topicStatus'][]= 'topic_sticky_unread';
                                    break;
                            }

                            $this->data['text_topic_status'][]=$this->language->get('text_topic_unread');
                        }
                    }
                }
            }

            $i++;
        }
    }

    private function post(){
        $this->data['content_type']='p';
        $this->data['navi_p_active']=' class="member-profile-active"';

        $this->data['text_topic']=$this->language->get('text_topic');
        $this->data['text_forum']=$this->language->get('text_forum');
        $this->data['text_replies']=$this->language->get('text_replies');
        $this->data['text_views']=$this->language->get('text_views');
        $this->data['text_last_post']=$this->language->get('text_last_post');
        $this->data['text_no_posts']=$this->language->get('text_no_posts');

        //pagination
        $url='action=p&uid=' . $this->request->get['uid'];
        $pagination = new Pagination();

        $pagination->total=$this->model_community_profile->getPostTotal($this->request->get);

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

        $pagination->page = $page;
        $pagination->limit = 20;
        $pagination->url = $this->url->link('community/profile', $url . '&page={page}');

        $this->data['pagination'] = $pagination->render();

        $start=($page-1)*$pagination->limit;

        $results=$this->model_community_profile->getPostInfo($this->request->get,$start,$pagination->limit);

        if(empty($results)){
            $this->data['has_posts']=FALSE;
        }else{
            $this->data['has_posts']=TRUE;
        }

        $this->data['post_infos']=array();

        $i=0;

        foreach($results as $result){
            $this->data['post_infos'][]=array(
                'post_subject'          =>      $result['post_subject'],
                'post_time'             =>      date($this->language->get('date_time_format_long'),$result['post_time']),
                'post_text'             =>      $this->parseSmiles($this->parseBbcode($this->parseSpacing($this->parseURL($result['post_text']))))
            );

            $this->data['post_infos'][$i]['post_link']=$this->url->link('community/viewtopic','fid=' . $result['forum_id'] . '&tid=' . $result['topic_id'] . '&pid=' .  $result['post_id'] . '#' . $result['post_id'],'SSL');

            $i++;
        }
    }

    private function parseSpacing($str){
        $str=nl2br($str);
        $str = str_replace("\t", '&nbsp; &nbsp;', $str);
        $str = str_replace('  ', '&nbsp; ', $str);
        $str = str_replace('  ', ' &nbsp;', $str);

        return $str;
    }

    private function parseBbcode($str){
        if($this->config->get('bbcode_parsing_enable')){
            $pattern=array();
            $pattern[]='/\[size=(\d+)\](.*)\[\/size\]/Uis';
            $pattern[]='/\[b\](.*)\[\/b\]/Uis';
            $pattern[]='/\[i\](.*)\[\/i\]/Uis';
            $pattern[]='/\[u\](.*)\[\/u\]/Uis';
            $pattern[]='/\[color=(#[0-9a-f]{3}|#[0-9a-f]{6}|[a-z\-]+)\](.*)\[\/color\]/Uis';

            if($this->config->get('bbcode_url_parsing_enable')){
                $pattern[]='/\[url\](.*)\[\/url\]/Uis';
                $pattern[]='/\[url=([^\[]+?)\](.*)\[\/url\]/Uis';
            }

            $pattern[]='/\[quote(?!&quot;.*&quot;)\](.*)\[\/quote\]/Uis';
            $pattern[]='/\[quote=&quot;(.*)&quot;\](.*)\[\/quote\]/Uis';
            $pattern[]='/\[code\](.*)\[\/code\]/Uis';

            if($this->config->get('bbcode_img_parsing_enable')){
                $pattern[]='/\[img\](.*)\[\/img\]/Uis';
            }

            if($this->config->get('bbcode_flash_parsing_enable')){
                $pattern[]='/\[flash\](.*)\[\/flash\]/Uis';
            }

            $pattern[]='/\[youtube\](http:\/\/)?(www\.)?youtube.com\/watch\?v=(.*)(&amp;\w*=.*)?\[\/youtube\]/Uis';

            $replace=array();
            $replace[]='<span style="font-size:\1%;">\2</span>';
            $replace[]='<strong>\1</strong>';
            $replace[]='<em>\1</em>';
            $replace[]='<span style="text-decoration:underline;">\1</span>';
            $replace[]='<span style="color:\1;">\2</span>';

            if($this->config->get('bbcode_url_parsing_enable')){
                $replace[]='<a href="\1" target="_blank">\1</a>';
                $replace[]='<a href="\1" target="_blank">\2</a>';
            }

            $replace[]='<blockquote class="bbcode_uncited"><div>\1</div></blockquote>';
            $replace[]='<blockquote class="bbcode_uncited"><div><dl><dt>\1 Wrote:</dt><dd>\2</dd></dl></div></blockquote>';
            $replace[]='<dl class="bbcode_code"><dt>CODE: <a href="javascript:void(0)" onclick="selectCode(this); return FALSE;">SELECT ALL</a></dt><dd><code>\1</code></dd></dl>';

            if($this->config->get('bbcode_img_parsing_enable')){
                $replace[]='<img src="\1" />';
            }

            if($this->config->get('bbcode_flash_parsing_enable')){
                $replace[]='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" height="400" width="480"><param name="quality" value="high" /><param name="movie" value="\1" /><embed height="400" pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="\1" type="application/x-shockwave-flash" width="480"></embed></object>';
            }

            $replace[]='<iframe width="560" height="315" src="http://www.youtube.com/embed/\3" frameborder="0" allowfullscreen></iframe>';

            $str=preg_replace($pattern,$replace,$str);
        }

        return $str;
    }

    private function parseSmiles($str){
        if($this->config->get('smiles_parsing_enable')){
            $smileCode=array(
                ':D',
                ':)',
                ';)',
                ':(',
                ':o',
                ':shock:',
                ':?',
                '8-)',
                ':lol:',
                ':x',
                ':P',
                ':-oops:',
                ':cry:',
                ':evil:',
                ':twisted:',
                ':roll:',
                ':!:',
                ':-?:',
                ':idea:',
                ':arrow:',
                ':|',
                ':mrgreen:',
                ':geek:',
                ':ugeek:',
            );

            $smileImage=array(
                '<img src="catalog/view/theme/default/image/smilies/01_very_happy.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/02_smile.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/03_wink.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/04_sad.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/05_surprised.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/06_shocked.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/07_confused.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/08_cool.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/09_langhing.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/10_mad.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/11_razz.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/12_embarrassed.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/13_cry.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/14_evil_or_very_mad.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/15_twisted_evil.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/16_rolling_eyes.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/17_exclamation.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/18_question.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/19_idea.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/20_arrow.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/21_neutral.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/22_mr._green.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/23_geek.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/24_uber_geek.gif" />'
            );

            $str=str_replace($smileCode,$smileImage,$str);
        }

        return $str;
    }

    private function parseURL($str){
        if($this->config->get('auto_url_parsing_enable')){
            $pattern=$replace=array();
            // matches an "xxxx://yyyy" URL at the start of a line, or after a space.xxxx can only be alpha characters. yyyy is anything up to the first space, newline, comma, double quote or <
            $pattern[]='/(^|[\n ])([\w]+?:\/\/[^ \"\n\r\t<]*)/is';
            // matches a "www|ftp.xxxx.yyyy[/zzzz]" kinda lazy URL thing.Must contain at least 2 dots. xxxx contains either alphanum, or "-". zzzz is optional.. will contain everything up to the first space, newline,comma, double quote or <.
            $pattern[]='/(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)/is';
            // matches an email@domain type address at the start of a line, or after a space. Note: Only the followed chars are valid; alphanums, "-", "_" and or ".".
            $pattern[]='/(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)/i';

            $replace[]='\\1<a href="\\2" target="_blank">\\2</a>';
            $replace[]='\\1<a href="http://\\2" target="_blank">\\2</a>';
            $replace[]='\\1<a href="mailto:\\2@\\3">\\2@\\3</a>';

            $str=preg_replace($pattern,$replace,$str);
        }

        return $str;
    }
}
?>